package LeetCode.leetcode;

/**
 * 二进制求和
 * @author: leiwenkang02@meituan.com
 * @date: 2018/8/24
 * @time: 11:31
 */
public class Test67二进制求和 {
    public static void main(String[] args) {
        System.out.println(addBinary("11", "1"));
    }
    public static String addBinary(String a, String b) {
        StringBuilder sb = new StringBuilder();
        char[] ch1 = a.toCharArray();
        char[] ch2 = b.toCharArray();
        int index1 = ch1.length - 1;
        int index2 = ch2.length - 1;
        int takeOver = 0;
        while (index1 >= 0 || index2 >= 0) {
            int chA = index1 >= 0 ? ch1[index1] - '0' : 0;
            int chB = index2 >= 0 ? ch2[index2] - '0' : 0;
            int val = chA ^ chB ^ takeOver;
            sb.append(val);
            takeOver = (chA & chB) | (chA & takeOver) | (chB & takeOver);
            index1--;
            index2--;
        }
        if (takeOver == 1) {
            sb.append(takeOver);
        }

        return sb.reverse().toString();


    }

}
